package com.lc.communication.util;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.Log;
import com.lc.communication.constants.ChannelConstant;
import com.lc.communication.vo.RequestVo;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentHashMap.KeySetView;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author liuhf17
 * @version 1.0.0
 * @ClassName ChannelMap.java
 * @Description TODO
 * @createTime 2024年06月11日 14:23:00
 */
public class ChannelMap {
    private static final Log log = Log.get();

    //发往服务端的通道
    public static final ConcurrentHashMap<String, Channel> CHANNEL_SERVER_MAP = new ConcurrentHashMap<>();

    //发往客户端的 通道
    public static final ConcurrentHashMap<String, Channel> CHANNEL_CLIENT_MAP = new ConcurrentHashMap<>();

    //服务端 心跳客户端错误次数
    public static final ConcurrentHashMap<String, AtomicInteger> CHANNEL_CLIENT_MAP_COUNT = new ConcurrentHashMap<>();


    public static final ConcurrentHashMap<String, String> resultMap = new ConcurrentHashMap<>();

    public static final ConcurrentHashMap<String, String> CLIENT_NAME_UUID = new ConcurrentHashMap<>();

    public static Object getRequestResult(RequestVo vo) {
        int index = 100;
        while (index > 0) {
            ThreadUtil.sleep(50);
            if (null == ChannelMap.resultMap.get(vo.getId())) {
                vo.setResBody("数据未找到匹配项 id：【" + vo.getId() + "】");
                return vo;
            }
            if (!ChannelConstant.WAIT.equals(ChannelMap.resultMap.get(vo.getId()))) {
                System.out.println(vo.getId() + " index success:" + index);
                String result = ChannelMap.resultMap.get(vo.getId());
                ChannelMap.resultMap.remove(vo.getId());
                return result;
            }
            log.info("{} index:{}", vo.getId(), index);
            index--;
        }
        return "获取数据失败";
    }


    public static void removeChannelClientMap(String key) {
        ChannelMap.CHANNEL_CLIENT_MAP.remove(key);
        KeySetView<String, String> nu = ChannelMap.CLIENT_NAME_UUID.keySet();
        String keyByValue = getKeyByValue(key);
        if (null != keyByValue) {
            ChannelMap.CLIENT_NAME_UUID.remove(keyByValue);
        }
    }

    public static String getKeyByValue(String value) {
        KeySetView<String, String> strings = CLIENT_NAME_UUID.keySet();
        for (String s : strings) {
            if (value.equals(CLIENT_NAME_UUID.get(s))) {
                return s;
            }
        }
        return null;
    }

}
